package main

import (
    "./cache"
    "./query"
    "config"
    "database/sql"
    "fmt"
    "html/template"
    "net/http"
    "strings"
    "time"
    "yotsuba"
)

func post(w http.ResponseWriter, r *http.Request,
    tmpl *template.Template, board *config.Board) {

    r.ParseForm()

    ip := strings.Split(r.RemoteAddr, ":")[0]
    threadNo := r.Form["thread_no"][0]
    name := r.Form["name"][0]
    email := r.Form["email"][0]
    subject := r.Form["subject"][0]
    comment := yotsuba.EscapeBBCode.Replace(r.Form["comment"][0])

    if name == "" {
        name = "Anonymous" // TODO: Should be configurable
    }

    // TODO: tripcodes.
    if len(comment) < board.GhostMinLength {
        errorPage(w, tmpl, "Comment too short.",
            "Post comment is below the minimum length.")
        return
    }
    if len(comment) > board.GhostMaxLength {
        errorPage(w, tmpl, "Comment too long.",
            "Post comment is beyond the maximum length.")
        return
    }

    row := query.Get(board.TableName, "insertPost").QueryRow(
        1, 1, time.Now(), name, nil, subject, email, nil, comment, false,
        threadNo, nil, nil, nil, ip, nil, false, "user")

    var postId, ghostId sql.NullInt64
    row.Scan(&postId, &ghostId)
    baseUrl := fmt.Sprintf("/%s/res/%s", board.Abbrev, threadNo)
    cache.Obsolete(baseUrl)
    postUrl := fmt.Sprintf("%s#a_%d%%2C%d",
        baseUrl, postId.Int64, ghostId.Int64)
    http.Redirect(w, r, postUrl, http.StatusFound)
    return
}
